package com.haojiang.mh.remote.adapter

import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.haojiang.mh.remote.bean.ControlLeftMenuBean
import com.haojiang.mh.remote.widget.ControlLeftMenuItemView

/**
 * 左侧的选择界面
 */
class ControlFragAdapter : RecyclerView.Adapter<ControlFragAdapter.HomeFragViewHolder>() {

    private val dataList = ArrayList<ControlLeftMenuBean>()
    private val viewList = ArrayList<ControlLeftMenuItemView>()
    private var iMenuItemClickListener: IMenuItemClickListener? = null


    fun setOnMenuItemClickListener(menuItemClickListener: IMenuItemClickListener?) {
        this.iMenuItemClickListener = menuItemClickListener
    }

    @Synchronized
    fun setData(list: List<ControlLeftMenuBean>) {
        viewList.clear()
        dataList.clear()
        dataList.addAll(list)
        for (i in 0 until dataList.size) {
            dataList.get(i).isClick = i == 0
        }
//        LogUtil.e("左边菜单刷新了")
        notifyDataSetChanged()
    }


    override fun getItemCount(): Int {
        return dataList.size
    }


    /**
     * 设置界面
     */
    override fun onBindViewHolder(holder: HomeFragViewHolder, position: Int) {
        val data = dataList.get(position)
        val itemView = holder.itemView as ControlLeftMenuItemView
        itemView.tag = data.code
        viewList.add(itemView)
        if (dataList.get(position).isClick) {
            itemView.setData(data, true)
        } else {
            itemView.setData(data, false)
        }

        itemView.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                for (i in 0 until dataList.size) {
                    dataList.get(i).isClick = false
                }
                dataList.get(position).isClick = true
                notifyDataSetChanged()
                iMenuItemClickListener?.onItemClick(dataList.get(position), position)
            }
        })
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeFragViewHolder {
        return HomeFragViewHolder(
            ControlLeftMenuItemView(parent.context)
        )
    }

    /**
     * adapter的ViewHolder类
     */
    class HomeFragViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {}


    interface IMenuItemClickListener {
        fun onItemClick(
            controlLeftMenuBean: ControlLeftMenuBean,
            position: Int
        )
    }
}
